﻿using DynamicQuartz.Schedule.Core;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DynamicQuartz.Schedule
{
    public static class DynamicQuartzExtensions
    {
        public static void AsDynamicQuartz(this IServiceCollectionQuartzConfigurator service)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Type[] types = assembly.GetTypes();

            var derivedClasses = types.Where(type => type.IsSubclassOf(typeof(QuartzScheduleBase)) && !type.IsAbstract);

            foreach (var derivedClassType in derivedClasses)
            {
                var derivedClassInstance = Activator.CreateInstance(derivedClassType);
                QuartzScheduleBase baseInstance = (QuartzScheduleBase)derivedClassInstance;

                Console.WriteLine($"Instance of {derivedClassType.Name} converted to QuartzScheduleBase && {baseInstance.Name}-{baseInstance.Cron}");


                // 获取 JobKey
                var jobKey = new JobKey(baseInstance.Name + DateTime.Now.ToString("yyyyMMddHHffmm"));

                // 注册 Job
                service.AddJob(derivedClassType, jobKey,opts => opts.WithIdentity(jobKey));

                // 注册 Trigger
                service.AddTrigger(opts => opts
                    .ForJob(jobKey)
                    .WithIdentity(baseInstance.Name + "-trigger")
                    .WithCronSchedule(baseInstance.Cron)
                );
            }
        }
    }
}
